<script type="text/javascript" src="<?=base_url()?>resource/js/layer/layer.js"></script>
<script type="text/javascript" src="<?= base_url() . 'resource/js/layer/layer.js' ?>" charset="utf-8"></script>
<!--top结束-->
<style type="text/css">
    .perssiom {
        margin: 10px 0px;
    }

    .perssiom .title ul li {
        float: left;
        padding: 10px 15px;
        list-style: none;
        border: 1px solid #e3e3e3;
        margin: 0px -1px -1px 0px;
    }

    .perssiom .title ul li a {
        color: #333;
        font-size: 13px;
        font-weight: 600;
    }

    .perssiom .items .iitem li {
        list-style: none;
    }

    .iitem > ul > li {
        border: 1px solid #eee;
        line-height: 35px;
    }

    .iitem table {
        border-collapse: collapse;
        width: 100%;
    }

    .iitem table tr td {
        border: 1px solid #e3e3e3;
        line-height: 25px;
        padding: 10px 5px;
    }
    .iitem table tr td label{
       font-size:12px;
       font-weight:normal;
    }
    .iitem table tr td input.l{
       margin:5px 5px 0px 0px;
    }
    .iitem table tr td li {
        width: 14%;
        float: left;
    }

    .bottom_bar {
        text-align: right;
        background-color: #eee;
        padding-right: 10px;
        height: 32px;
        line-height: 32px;

    }

</style>

<!--菜单 start-->
<?php $this->load->view('defaults/common/left');?>
<!--菜单 end-->
<div id="content">
    <div class="page-header">
        <div class="container-fluid">
          <h1><?=lang('menu_yhgl')?></h1>
          <?=$this->breadcrumb->generateHTML();?>
        </div>
    </div>
    <div class="container-fluid">
        <div class="panel panel-default">
          <div class="panel-heading">
            <h3 class="panel-title"><i class="fa fa-pencil"></i><?=lang('menu_permission_maintain')?></h3>
          </div>
          <div class="panel-body">
            <div id="contents">
                <div style="text-align: center;">
                    <i>蓝色背景表示该权限已作为菜单使用;"+"表示该权限下有未展开的子权限,点击可展开.</i>
                    <button type="button" class="J-add-permission">添加权限</button>
                </div>
            </div>
          </div>
        </div>
    </div>
  

</div>
<script type="text/template" id="permissionInfo">
<div>
    <form action="" method="post">
        <div class="form-h">
            <span>父级权限：</span>
            <select id="J-linkage-g1" class="" style="" data-top="0" data-group="g1" data-pids="" data-filter="" data-first="--顶级权限--,--可选--" data-url="<?= blang_url('users/member/getPermissionChildren') ?>"></select>
            <input type="hidden" data-group="g1" data-onlylast="0"  data-level="5" name="parent_id" />
            <input type="hidden" name="id">
            <p>提示语</p>
        </div>

        <div class="form-h">
            <span>描述：</span>
            <input type="text" name="description">
            <p>权限显示的名称</p>
        </div>

        <div class="form-h">
            <span>英文描述：</span>
            <input type="text" name="description_en">
            <p>权限显示的英文名称</p>
        </div>

        <div class="form-h">
            <span>类名：</span>
            <input type="text" name="class_name">
            <p>后台对应的类文件名,包含类的目录</p>
        </div>

        <div class="form-h">
            <span>函数名：</span>
            <input type="text" name="function_name">
            <p>所对应的类的方法名</p>
        </div>

        <div class="form-h">
            <span>排序值：</span>
            <input type="number" name="sort" value="255">
            <p>排序值1-255,升序排列</p>
        </div>

        <div class="form-h">
            <span>是否作为菜单显示：</span>
            <label><input type="radio" name="is_menu" value="1">是</label>&nbsp;&nbsp;
            <label><input type="radio" name="is_menu" value="0" checked>否</label>
            <p>是否在后台中作为菜单显示出来</p>
        </div>
    </form>
</div>
</script>

<style type="text/css">
.form-h{padding:5px 0;}
.form-h > span,
.form-h > input,
.form-h > label,
.form-h > textarea,
.form-h > select{vertical-align:middle;}
.form-h > input{width: 50%;}
.form-h > span{display:inline-block;width:120px;overflow:hidden;white-space: nowrap;text-overflow: ellipsis;padding-right: 10px;text-align:right;line-height: 26px;}
.form-h p{display:block;font-size:0.8em;color:#999;padding-left: 135px;padding-top: 2px;}
.form-h p.right,
.form-h p.success{color:#666;}
.form-h p.wrong,
.form-h p.error{color:#f88;}
ul.my-tree {padding: 0px; list-style: none; overflow: hidden;}
ul.my-tree ul{
    margin-left: 20px;
    padding-left: 40px;
    list-style: none;
    border-left:1px solid #ccc;
    transition: all 1s ease 0s;
}
ul.my-tree div.fold + ul{
    opacity: 0;
    height: 0;
    overflow-y: hidden;
}
ul.my-tree div.unfold + ul{
    opacity: 1;
    height: auto;
    overflow-y: auto;
}


ul.my-tree div{
    padding: 2px 0;
    display: inline-block;
    cursor: pointer;
}
ul.my-tree div::before{
    content:' ';
    display: inline-block;
    width: 40px;
    margin-left: -40px;
    border-top:1px solid #ccc;
}

ul.my-tree a{
    height: 16px;
    padding: 0 8px;
    font-size: 10px;
    color: #fff;
    border-radius:8px;
    line-height: 16px;
    display: none;
}
ul.my-tree a:hover{
    cursor: pointer;
}
ul.my-tree a.edit{background: #1aa8f4;}
ul.my-tree a.add-sub{background: green;}
ul.my-tree a.del{background: red;}

ul.my-tree div:hover a{
    display: inline-block;
}

ul.my-tree span{
    display: inline-block;
    height:24px;
    line-height: 24px;
    padding: 0 20px;
    border-radius: 12px;
    border: 1px solid #eee;
    position: relative;
}
ul.my-tree div[data-menu="1"] span{
    color:#fff;
    background: #1aa8f4 !important;
}

ul.my-tree div[data-child="1"] span::after{
    content:'+';
    display: inline-block;
    width: 12px;
    height: 12px;
    vertical-align: middle;
    line-height: 12px;
    text-align: center;
    color: #fff;
    border-top:1px solid #ccc;
    border-radius:6px;
    background:green;
    position: absolute;
    right: 3px;
    top:5px;
}
ul.my-tree div.unfold[data-child="1"] span::after{
    content:'-';
}
</style>


<script type="text/javascript">
//生成权限树
function createTree(data){
    $(document).on('click','.my-tree div.fold span',function(){
        $(this).parent().addClass('unfold').removeClass('fold');
    });
    $(document).on('click','.my-tree div.unfold span',function(){
        $(this).parent().addClass('fold').removeClass('unfold');
    });
    var render = function(data){
        var html = '';
        var tpl =  '<div class="unfold" data-id="__id__" data-c="__c__" data-a="__a__" data-sort="__sort__" data-title="__title__" data-title_en="__title_en__" data-menu="__menu__" data-child="__child__" id="permission-__id__">\
                        <span>__title__</span>\
                        <a class="edit">编辑</a>\
                        <a class="add-sub">添加子级</a>\
                        <a class="del">删除</a>\
                    </div>';
        for(var i in data){
            var haveChild = (data[i].children && data[i].children.length > 0) ? true : false;
            html += '<li class="clearfix">';
            html += tpl.replace(/__id__/g, data[i].id)
                       .replace(/__c__/g, data[i].c)
                       .replace(/__a__/g, data[i].a)
                       .replace(/__sort__/g, data[i].sort)
                       .replace(/__menu__/g, data[i].is_menu)
                       .replace(/__child__/g, haveChild ? 1 : 0)
                       .replace(/__title__/g, data[i].title)
                       .replace(/__title_en__/g, data[i].title_en || '');
            if(haveChild){
                html += '<ul>';
                html += render(data[i].children);
                html += '</ul>';
            }
            html += '</li>';
        }
        return html;
    }
    var tree = '<ul class="my-tree">';
    tree += render(data);
    tree += '</ul>';
    return tree;
}
//获取权限父id串
function getParentIds(id){
    var ids;
    $.ajax({
        async:false,
        url:"<?= blang_url('users/member/getPermissionParentIds') ?>",
        data:{id:id},
        success:function(response){
            ids = response.data;
        }
    });
    return ids.join(',');
}

$(function(){
    var data = <?= json_encode($tree) ?>;
    $('#contents').append(createTree(data));
});


$(document).on('click','.my-tree div .edit',function(){
    var url = "<?=blang_url('users/member/UpdatePermission')?>";
    var tpl = $('#permissionInfo').html().toString();
    var id = $(this).parent().data('id');
    var c = $(this).parent().data('c');
    var a = $(this).parent().data('a');
    var title = $(this).parent().data('title');
    var title_en = $(this).parent().data('title_en');
    var sort = $(this).parent().data('sort');
    var is_menu = $(this).parent().data('menu');
    var index = layer.open({
        title:'权限编辑',
        type: 1,
        btn:['保存','取消'],
        area: ['650px', '480px'],
        content: tpl,
        yes:function(){
            $('#layui-layer'+index).find('form').submit();
        },
        btn2:function(){
            layer.close(index);
        },
        success: function(layero, index){
            var ids = getParentIds(id);
            $(layero).find('#J-linkage-g1').data('pids', ids);
            $(layero).find('#J-linkage-g1').data('filter', id);
            J_linkage("#J-linkage-g1");
            $(layero).find('[name="id"]').val(id);
            $(layero).find('[name="description"]').val(title);
            $(layero).find('[name="description_en"]').val(title_en);
            $(layero).find('[name="class_name"]').val(c);
            $(layero).find('[name="function_name"]').val(a);
            $(layero).find('[name="sort"]').val(sort);
            $(layero).find('[name="is_menu"][value="'+is_menu+'"]').prop('checked',true);
            $(layero).find('form').attr('action',url);
        }
    });
});

$(document).on('click','.my-tree div .add-sub',function(){
    var url = "<?=blang_url('users/member/AddPermission')?>";
    var tpl = $('#permissionInfo').html().toString();
    var id = $(this).parent().data('id');
    var c = $(this).parent().data('c');
    var index = layer.open({
        title:'添加子权限',
        type: 1,
        btn:['提交','取消'],
        area: ['650px', '480px'],
        content: tpl,
        yes:function(){
            $('#layui-layer'+index).find('form').submit();
        },
        btn2:function(){
            layer.close(index);
        },
        success: function(layero, index){
            var ids = getParentIds(id);
            $(layero).find('#J-linkage-g1').data('pids', ids+','+id);
            $(layero).find('input[data-group="g1"]').data('level', ids.split(',').length);
            J_linkage("#J-linkage-g1", function($sel){
                $sel.prop('disabled',true);
            });
            $(layero).find('[name="class_name"]').val(c);
            $(layero).find('form').attr('action',url);
        }
    });
    
});

$(document).on('click','.my-tree div .del',function(){
    var id = $(this).parent().data('id');
    layer.confirm('确定要删除吗?该权限下如果有子权限,子权限也将被删除!', {icon: 3, title:'警告'}, function(index){
        var url = "<?=blang_url('users/member/DeletePermission')?>";
        $.ajax({
            url:url,
            type:'post',
            data:{id:id},
            success:function(response){
                layer.msg(response.message);
                layer.close(index);
                if (response.success) {
                    location.reload();
                }
            }
        });
    });
});

$(document).on('click','.J-add-permission',function(){
    var url = "<?=blang_url('users/member/AddPermission')?>";
    var tpl = $('#permissionInfo').html().toString();
    var index = layer.open({
        title:'添加子权限',
        type: 1,
        btn:['提交','取消'],
        area: ['650px', '480px'],
        content: tpl,
        yes:function(){
            $('#layui-layer'+index).find('form').submit();
        },
        btn2:function(){
            layer.close(index);
        },
        success: function(layero, index){
            $(layero).find('#J-linkage-g1').data('pids', 0);
            J_linkage("#J-linkage-g1");
            $(layero).find('form').attr('action',url);
        }
    });
});

</script>






<script>
function J_linkage(sele, fn){
    if(!(this instanceof arguments.callee)){
        return new arguments.callee(sele, fn);
    }
    this.obj        = $(sele);
    this.group      = this.obj.data('group'),//联动菜单的编组号,以能支持一个页面多个联动菜单
    this.top        = this.obj.data('top').toString(),//第一级被选中的菜单
    this.url        = this.obj.data('url'),
    this.first      = this.obj.data('first').replace(/^,|,$/g,'').split(','),//每一级附加的第一个option
    this.pids       = this.obj.data('pids').toString().replace(/^,|,$/g,''),//在编辑时有值,新增时无值
    this.filter     = this.obj.data('filter'),//要过滤的值
    this.eleclass   = this.obj.attr('class') + ' J-linkage',
    this.style      = this.obj.attr('style');
    this.$input     = $('input[data-group="'+ this.group +'"]');
    this.onlylast   = this.$input.data('onlylast');//一般情况下只取最后一级的值
    this.level      = this.$input.data('level');//限定级数,比如只选择到城市,而不是具体到街道

    this.pids = this.pids ? this.pids.split(',') : [];
    
    if(this.top !== ''){
        this.pids.length === 0 && this.pids.push(this.top);
        for(var i in this.pids){
            if(this.pids[i] == this.top)
                this.pids = this.pids.slice(i);
        }
    }
    var _this=this;

    //绑定联动菜单事件
    $(document).delegate('.J-linkage[data-group="'+ this.group +'"]', 'change', function(){
        $(this).nextAll('.J-linkage').remove();
        //如果选择的是--请选择--
        if($(this).val() == ''){
            !_this.onlylast && _this.$input.val($(this).prev('.J-linkage').val());
            return;
        }else{
            _this.$input.val('');
        }
        _this.pids=[$(this).val()];//查询单级联动
        _this.linkage();
    });
    //根据pids查询联动菜单
    this.linkage=function(){
        if (this.pids.length < 1)return;
        var pid         = this.pids.shift();
        var add_level   = $('.J-linkage[data-group="'+ this.group +'"]').length;//添加第几级联动
        if (add_level >= this.level) {
            this.$input.val(pid);
            if (typeof(fn) === 'function') {
                fn($('.J-linkage[data-group="'+ this.group +'"]'), this.$input);
            }
            return;
        }
        var first_txt = this.first[add_level] || this.first[add_level-1] || this.first[1];
        $.ajax({
            async:false,
            url:_this.url,
            data:'parent_id=' + pid,
            success:function(response){
                if(response.success && response.data.length > 0){
                    var html='<select class="'+ _this.eleclass +'" data-group="'+ _this.group +'" style="'+ _this.style +'">';
                    html +='<option value="">'+ first_txt +'</option>';
                    for(var i in response.data){
                        var id = response.data[i].id;
                        if(id == _this.filter)continue;
                        var selected = (_this.pids[0] && id.toString() ==_this.pids[0].toString()) ? ' selected' : '';
                        html +='<option value="'+ id + '"' + selected + '>' + response.data[i].title +'</option>';
                    }
                    html += '</select>';
                    _this.$input.before(html);
                    _this.obj.remove();
                    var value = _this.onlylast ? '' : pid;
                    _this.$input.val(value);
                    _this.linkage();
                }else{
                    _this.$input.val(pid);
                    if (typeof(fn) === 'function') {
                        fn($('.J-linkage[data-group="'+ _this.group +'"]'), _this.$input);
                    }
                }
            }
        });
    }
    this.linkage();
}
</script>